import React, { useState } from 'react'
import styles from './index.module.scss'
import MyNavBar from '@/components/MyNavBar'
import { WhiteSpace, WingBlank, Flex, Toast } from 'antd-mobile'
import { login } from '@/api/user'
import { setToken } from '@/utils/token'

function Login ({ history, location }) {
  const [username, setUsername] = useState('test2')
  const [password, setPassword] = useState('test2')

  const userLogin = async () => {
    const res = await login({ username, password })
    if (res.data.status === 200) {
      setToken(res.data.body.token)

      if (location.state && location.state.from) {
        history.replace(location.state.from)
      } else {
        history.goBack()
      }
    } else {
      Toast.info(res.data.description, 1.5)
    }
  }

  return (
    <div className={styles.root}>
      <MyNavBar>账号登录</MyNavBar>
      <WhiteSpace size='xl' />
      <WingBlank size='lg'>
        <form>
          <div className={styles.formItem}>
            <input
              placeholder='请输入账号'
              className={styles.input}
              type='text'
              value={username}
              onChange={e => setUsername(e.target.value)}
            />
          </div>
          <div className={styles.formItem}>
            <input
              placeholder='请输入密码'
              className={styles.input}
              type='password'
              value={password}
              onChange={e => setPassword(e.target.value)}
            />
          </div>
          <div className={styles.formSubmit}>
            <div onClick={() => userLogin()} className={styles.submit}>
              登录
            </div>
          </div>
        </form>
        <div className={styles.backHome}>
          <Flex.Item>
            <a href='#'>还没有账号，去注册~</a>
          </Flex.Item>
        </div>
      </WingBlank>
    </div>
  )
}

export default Login
